package servlet;

import model.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "user_login", urlPatterns = "/user_login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("login_username");
        String password = request.getParameter("login_password");

        // 调用service处理登录
        User user = userService.login(username, password);

        if(user != null) {
            // 登录成功，将用户信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 根据用户类型跳转到不同页面
            if(user.isAdmin()) {

                response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
            } else {

                response.sendRedirect(request.getContextPath() + "/user_center.jsp");
            }
        } else {
            // 登录失败
            System.out.println("用户登录失败：" + username);
            request.setAttribute("msg", "用户名或密码错误！");
            request.getRequestDispatcher("/user_login.jsp").forward(request, response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET请求直接跳转到登录页面
        request.getRequestDispatcher("/user_login.jsp").forward(request, response);
    }
} 